
package com.b2c.common.third.ali;

import com.alibaba.fastjson.JSONObject;
import com.b2c.common.third.ali.vo.TokenVo;
import com.b2c.common.utils.HttpUtil;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Map;

/**
 * 1688获取数据类
 */

public class AliClient {
    private static String appId = "9380846";
//    private static String appId = "5207696";
    private static String appSecret = "MJC3doohMxCG";
//    private static String appSecret = "T0pXV8kVya";

    /**
     * 获取AppId
     *
     * @return
     */
    public static String getAppId() {
        return appId;
    }

    /**
     * 获取AppId
     *
     * @return
     */
    public static String getAppSecret() {
        return appSecret;
    }

    /**
     * 1.授权回调
     *
     * @param returnUrl 回调地址
     * @return
     */
    public static String getAliAuthorizeUrl(String returnUrl) {
        return "https://auth.1688.com/oauth/authorize?client_id=" + appId + "&site=1688&redirect_uri=" + returnUrl;
    }


    /**
     * 2.根据回调code 获取令牌
     *
     * @param code
     * @return
     * @throws IOException
     * @throws InterruptedException
     */
    public static TokenVo getTokenVo(String code, String returnUrl) throws IOException, InterruptedException {
        String url = "https://gw.open.1688.com/openapi/http/1/system.oauth2/getToken/" + appId + "?grant_type=authorization_code&need_refresh_token=true&client_id=" + appId + "&client_secret=" + appSecret + "&redirect_uri=" + returnUrl + "&code=" + code;
        HttpClient client = HttpClient.newBuilder().build();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .POST(HttpRequest.BodyPublishers.ofString(""))
                .build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.statusCode());
        return JSONObject.parseObject(response.body(), TokenVo.class);
    }


    public static String sendUrl(Map<String, String> params2, String sendUrl2) {
        try {
            String sendParams = HttpUtil.map2Url(params2);
            System.out.println("sendParams:" + sendParams);
            HttpResponse<String> response2 = HttpUtil.doPost(sendUrl2, sendParams);
            return response2.body();
        } catch (Exception e) {
            return null;
        }
    }


    public static void main(String[] args) {

    }
}

